package com.blb.community.service.impl;

import com.blb.community.entity.SysMenu;
import com.blb.community.entity.vo.MenuVo;
import com.blb.community.mapper.SysMenuMapper;
import com.blb.community.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 帅帅
 * @since 2022-07-02
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<MenuVo> queryAllMenuByUserName(String username) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<MenuVo> menuVos = (List<MenuVo>) ops.get("Menus::" + username);
        if (null != menuVos) {
            return menuVos;
        } else {
            List<MenuVo> menuVos1 = sysMenuMapper.queryAllMenuByUserName(username);
            if (null != menuVos1) {
                ops.set("Menus::" + username, menuVos1);
                return menuVos1;
            }
        }
        return null;
    }


    @Override
    public List<MenuVo> selectAllMenus(String menuName, String status) {
        return sysMenuMapper.selectAllMenus(menuName, status);
    }


    @Override
    public Integer addMenus(SysMenu sysMenu, String userName) {
        int insert = sysMenuMapper.insert(sysMenu);
        if (insert > 0) {
            Set<String> keys = redisTemplate.keys("Menus::" + userName);
            redisTemplate.delete(keys);
        }
        return insert;
    }

    @Override
    public Integer updateMenu(SysMenu sysMenu, String userName) {
        int i = sysMenuMapper.updateById(sysMenu);
        if (i > 0) {
            Set<String> keys = redisTemplate.keys("Menus::" + userName);
            redisTemplate.delete(keys);
        }
        return i;
    }

    @Override
    public Integer deleteMenu(Long id, String userName) {
        int i = sysMenuMapper.deleteById(id);
        if (i > 0) {
            Set<String> keys = redisTemplate.keys("Menus::" + userName);
            redisTemplate.delete(keys);
        }
        return i;
    }


}
